package gen

import (
	"database/sql"
	"encoding/xml"
	"fmt"
	"io/ioutil"

	_ "github.com/go-sql-driver/mysql"
)

type DBConfig struct {
	DriverName string `xml:"driverName"`
	User       string `xml:"user"`
	Passwd     string `xml:"passwd"`
	IP         string `xml:"ip"`
	Prot       string `xml:"prot"`
	Database   string `xml:"database"`
}

var ConfDir string
var config DBConfig
var Db *sql.DB

type ClouMsg struct {
	ColumnName    string
	DataType      string
	ColumnComment string
}

func DbInit(filePath string) {
	fmt.Println("初始化数据库连接...")
	content, err := ioutil.ReadFile(ConfDir + filePath)
	if err != nil {
		fmt.Println("读取数据库配置文件出错:", err.Error())
		return
	}
	err = xml.Unmarshal(content, &config)
	if err != nil {
		fmt.Println("解析数据库配置错误:", err.Error())
		return
	}
	var dbUrl = fmt.Sprint(config.User, ":", config.Passwd, "@tcp(", config.IP, ":", config.Prot, ")/", config.Database, "?charset=UTF8")
	fmt.Println("database:", dbUrl)
	//fmt.Printf("%+v\n", config)
	Db, err = sql.Open(config.DriverName, dbUrl)
	if err != nil {
		fmt.Println("打开数据链接错误:", err.Error())
		return
	}
	//defer Db.Close()
	Db.SetMaxIdleConns(1)
	Db.SetMaxOpenConns(1)
}

func Query(table string) []ClouMsg {
	rows, err := Db.Query("SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? and TABLE_NAME = ?", config.Database, table)
	if err != nil {
		fmt.Println("查询数据表信息错误:", err.Error())
		return nil
	}
	defer rows.Close()
	var columns = make([]ClouMsg, 0, 1)
	for rows.Next() {
		var columnName string
		var dataType string
		var columnComment string
		err := rows.Scan(&columnName, &dataType, &columnComment)
		if err != nil {
			fmt.Println("SCAN数据错误:", err.Error())
			return nil
		}
		var clouMsg = ClouMsg{columnName, dataType, columnComment}
		columns = append(columns, clouMsg)
	}
	fmt.Printf("%+v\n", columns)
	return columns
}
